var logger = require('../../common').logger;
var query = require('../../common').Query;
var map = require('../../common').Mapping;
var AdvanceCron = require('../../common/cron').cronProcess;
var mailer = require('../../common').Mailer;

var cronConfig = {
    freq: "0 0 8 * * *", //every morning check if time to publish
    monitor: "0 59 * * * *", //every hour check cron table status
    scope: {
        query: query,
        map: map,
        mailer: mailer
    },
    worker: function () {
        var self = this;
        self.query(self.map.sql.findSetting, {}, {}, function (rows) {
            var setting = rows[0];
            if (setting.on_off === 'on') {
                var interval = parseInt(setting.freq.split("/")[0]);
                var day = parseInt(setting.freq.split("/")[1]) + 1;
                if ((new Date().getDay()) === day) {
                    self.query(self.map.sql.findPlan, {}, {status: "latest"}, function (latest) {
                        if (latest.length == 0 || new Date().valueOf() - (new Date(latest[0].start_date)).valueOf() >=
                            interval * 86400 * 1000 * 7) {
                            var nowDate = new Date().Format('yyyy-MM-dd');
                            var endDate = new Date(new Date().valueOf() + interval * 86400 * 1000 * 7).Format('yyyy-MM-dd');
                            var nameTpl = setting.name_tpl.replace("[start_date]", nowDate).replace("[end_date]", endDate);
                            var nextTpl = setting.next_plan_tpl.replace("[start_date]", nowDate).replace("[end_date]", endDate);
                            var obj = {
                                plan_name: nameTpl,
                                start_date: nowDate,
                                end_date: endDate,
                                next_plan: nextTpl,
                                updatedAt: new Date().Format('yyyy-MM-dd hh:mm')
                            };
                            self.query("UPDATE plan SET status = 'history' WHERE status <> 'history'", {}, {}, function () {
                                self.query(self.map.sql.addPlan, {}, obj, function (data) {
                                    self.query("SELECT email FROM USER WHERE role='manager'", {}, {}, function (addrs) {
                                        var addr = "";
                                        addrs.forEach(function (e) {
                                            addr += (e.email + ";");
                                        });
                                        self.mailer({
                                            sendTo: addr, html: "各位研发组长:<br />" +
                                            "&nbsp;&nbsp;大家好!新的双周计划已发布,请于截止日期:<span style='color: red'>"
                                            + endDate + "</span>之前登陆系统填写计划安排"
                                        });
                                    });
                                });
                            });
                        }
                    })
                }
            }
        });
    }
};

var cronInstance = new AdvanceCron(cronConfig);
exports.cronInstance = cronInstance;